#include "../include/ProtocolParser.h"
#include <sys/socket.h>
#include <vector>
#include <iostream>

using std::vector;
using std::cout;
using std::endl;
using std::to_string;
using std::cin;

void ProtocolParser::displayPageNav(int curPage,int totalPage){
    cout<<"[<] ";
    for(int i=1;i<=totalPage;i++){
        if(i == curPage){
            //给当前页加高亮
            cout<<"\033[38;5;1m"<<curPage<<"\033[0m"<<" ";
        }else{
            cout<<i<<" ";
        }
    }
    cout<<"[>]"<<endl;
}

void ProtocolParser::handleMessage(const string &msg){
    auto msgJson = json::parse(msg);
    string messageId=msgJson["messageId"];
    string message=msgJson["message"];

    if(messageId == "50"){
        cout<<message<<endl;
    }else if(messageId == "100"){
        auto messJson=json::parse(message);
        vector<string> keywords = messJson["keywords"];
        cout<<"KEYWORDS: "<<endl;
        for(auto & keyword: keywords){
            cout<<keyword<<endl;
        }
    }else if(messageId == "200"){
        auto messJson = json::parse(message);
        vector<json> items = messJson["items"];

        int page=0;
        int size=items.size();

        bool exit=false;

        if(size == 0){
            cout<<"查无结果"<<endl;
            exit=true;
        }

        while(!exit){
            
            for (int i = page * pageSize; i < size && i < (page + 1) * pageSize; i++)
            {
                

                string title = items[i]["title"];
                string link = items[i]["link"];
                string content = items[i]["content"];
                cout << "文章ID:" << i + 1 << endl;
                cout << "标题: " << title << endl;
                cout << "URL: " << link << endl;
                cout << "摘要: " << content << endl
                     << endl;
            }

            int totalPage=size/pageSize+(size%pageSize!=0);
            displayPageNav(page+1,totalPage);

            string changePage;
            while(1){
                cin>>changePage;
                if(changePage=="<"){
                    if(page!=0){
                        --page;
                    }
                    break;
                }else if(changePage==">"){
                    if(page<totalPage-1){
                        ++page;
                    }
                    break;
                }else if(changePage == "q"||changePage == "Q"){
                    exit=true;
                    break;
                }else{
                    cout<<"输入错误"<<endl;
                    cout<<"输入'<'上一页，输入'>'下一页"<<endl;
                }
            }
            cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');//清除无效字符
        }
    }
}

string ProtocolParser::jsonMsgPack(const string &msgId,const string &msg){
    json msgJson;
    msgJson["messageId"]=msgId;
    msgJson["message"]=msg;
    return msgJson.dump();
}
